<script setup lang="ts">
import { addFlagshipCoupon, detailFlagshipCoupon, updateFlagshipCoupon } from '@fl/api/flagship/flagship-coupon'
import FlUpload from '@fl/components/fl-upload.vue'
import { ElMessage } from 'element-plus'
import { useDicts } from '../hooks/use-dicts'
import { isUnifyTheSCC } from '@fl/utils/validate'

const emit = defineEmits(['storeformchange'])
const route = useRoute()
const { dicts: { EnterpriseType } } = useDicts()

type formType = {
    enterpriseAbbreviation?: string
    enterpriseIntroduction?: string
    enterpriseType?: string
    enterpriseName?: string
    enterpriseTell?: string
    companyIntroduction?: string
    companyLabel?: string
    companyContactName?: string
    companyPhone?: string
    companyLogo?: string
    companyName?: string
    unifiedSocialCreditIdentifier?: string
    programAppid?: string
    programId?: string
    jumpProgram?: string
}
const defaultform = ref<formType>({
    enterpriseAbbreviation: '',
    enterpriseIntroduction: '',
    enterpriseType: '',
    enterpriseName: '',
    enterpriseTell: '',
    companyIntroduction: '',
    companyLabel: '',
    companyContactName: '',
    companyPhone: '',
    companyLogo: '',
    companyName: '',
    unifiedSocialCreditIdentifier: '',
    programAppid: '',
    programId: '',
    jumpProgram: '0',
})
const form = ref<formType>({
    enterpriseAbbreviation: '',
    enterpriseIntroduction: '',
    enterpriseType: '',
    enterpriseName: '',
    enterpriseTell: '',
    companyIntroduction: '',
    companyLabel: '',
    companyContactName: '',
    companyPhone: '',
    companyLogo: '',
    companyName: '',
    unifiedSocialCreditIdentifier: '',
    programAppid: '',
    programId: '',
    jumpProgram: '0',
})
const storeRef = ref<any>()
const isLoading = ref<boolean>(false)
const enterVisible = ref<boolean>(false)

function validatorunifiedSocialCreditCode(rule, value, callback) {
    if (value && !isUnifyTheSCC(value)) {
        callback(new Error('请输入正确的统一社会信用代码'))
    }
    else {
        callback()
    }
}

const rules = {
    enterpriseName: [{ message: '请输入企业名称', required: true, trigger: 'blur' }],
    enterpriseType: [{ message: '请选择企业类型', required: true, trigger: 'blur' }],
    companyContactName: [{ message: '请输入品牌联系人', required: true, trigger: 'blur' }],
    companyPhone: [
        { message: '请输入品牌联系人电话', required: true, trigger: 'blur' },
        {
            message: '请输入正确的电话号码',
            pattern: /^1[3-9]\d{9}$/,
            trigger: 'blur',
        },
    ],
    enterpriseTell: [
        { message: '请输入企业电话', trigger: 'blur' },
        {
            message: '请输入正确的电话号码',
            pattern: /^(1[3-9]\d{9}|(0\d{2,3}-?)?[1-9]\d{6,7})$/,
            trigger: 'blur',
        },
    ],
    unifiedSocialCreditIdentifier: [
        { message: '请输入正确的信用代码', trigger: 'blur' },
        { message: '请输入正确的信用代码', validator: validatorunifiedSocialCreditCode },
    ],
    companyName: [{ message: '请输入品牌名称', required: true, trigger: 'blur' }],
    programId: [{ message: '请输入', required: true, trigger: 'blur' }],
    programAppid: [{ message: '请输入', required: true, trigger: 'blur' }],
}

function updateForm(data: formType) {
    Object.assign(form.value, data)
    isLoading.value = false
    form.value.companyLogo = data.companyLogo || ''
    // form.value.jumpProgram = data.programAppid ? '1' : '0'
}

// 校验表单数据
function validatechange(key) {
    storeRef.value.validate((valid) => {
        if (valid) {
            if (
                form.value.enterpriseName
                && form.value.enterpriseName.split('').filter(Boolean).length > 500
            ) {
                return false
            }
            if (key === '1') {
                // 修改品牌信息

                updateFlagshipCoupon(form.value).then((res) => {
                    if (res.code === 200) {
                        ElMessage.success(res.msg)
                    }
                    else {
                        ElMessage.warning(res.msg)
                    }
                })
            }
            else {
                addFlagshipCoupon(form.value).then((res) => {
                    if (res.code === 200) {
                        updateForm(defaultform.value as formType)
                        emit('storeformchange', res.data)
                        ElMessage.success(res.msg)
                    }
                    else {
                        ElMessage.warning(res.msg)
                    }
                })
            }
        }
    })
}
onMounted(() => {
    if (route.query.id) {
        isLoading.value = true
        enterVisible.value = true
        detailFlagshipCoupon(route.query.id).then((res) => {
            updateForm(res.data as formType)
        })
    }
    else {
        enterVisible.value = false
    }
})
defineExpose({
    validatechange,
})

// 信用代码
function filterInput(value) {
    form.value.unifiedSocialCreditIdentifier = value.replace(/[^a-z0-9]/gi, '')
}

// 手机号、座机号
function filterTell(value) {
    form.value.enterpriseTell = value.replace(/[^\d-]/g, '')
}

// 品牌联系人
function filterPhone(value) {
    form.value.companyPhone = value.replace(/\D/g, '')
}
</script>

<template>
    <el-skeleton v-if="isLoading" />

    <el-form v-else
             ref="storeRef"
             :inline="true"
             :model="form"
             :rules="rules"
             label-width="150px"
    >
        <div class="left">
            <el-row>
                <el-col :span="14">
                    <el-form-item label="企业名称："
                                  prop="enterpriseName"
                    >
                        <el-input v-model="form.enterpriseName"
                                  :disabled="enterVisible"
                                  maxlength="20"
                        />
                    </el-form-item>

                    <el-form-item label="企业类型："
                                  prop="enterpriseType"
                    >
                        <el-select v-model="form.enterpriseType">
                            <el-option v-for="item in EnterpriseType"
                                       :key="item.value"
                                       :label="item.label"
                                       :value="item.value"
                            />
                        </el-select>
                    </el-form-item>

                    <el-form-item label="企业简称："
                                  prop="enterpriseAbbreviation"
                    >
                        <el-input v-model="form.enterpriseAbbreviation"
                                  maxlength="20"
                        />
                    </el-form-item>

                    <el-form-item label="统一社会信用代码："
                                  prop="unifiedSocialCreditIdentifier"
                    >
                        <el-input v-model="form.unifiedSocialCreditIdentifier"
                                  maxlength="18"
                                  @input="filterInput"
                        />
                    </el-form-item>

                    <el-form-item label="企业电话："
                                  prop="enterpriseTell"
                    >
                        <el-input v-model="form.enterpriseTell"
                                  maxlength="13"
                                  @input="filterTell"
                        />
                    </el-form-item>

                    <el-form-item label="品牌名称："
                                  prop="companyName"
                    >
                        <el-input v-model="form.companyName"
                                  maxlength="20"
                                  placeholder="请输入"
                        />
                    </el-form-item>

                    <el-form-item label="品牌联系人："
                                  prop="companyContactName"
                    >
                        <el-input v-model="form.companyContactName"
                                  maxlength="20"
                                  placeholder="请输入"
                        />
                    </el-form-item>

                    <el-form-item label="品牌联系人电话："
                                  prop="companyPhone"
                    >
                        <el-input v-model="form.companyPhone"
                                  placeholder="请输入"
                                  maxlength="11"
                                  @input="filterPhone"
                        />
                    </el-form-item>

                    <el-form-item label="品牌标签：">
                        <div class="txtar">
                            <el-input v-model="form.companyLabel"
                                      type="textarea"
                                      placeholder="一个标签一行，最多保留四个标签"
                            />
                        </div>
                    </el-form-item>

                    <el-form-item label="公司介绍：">
                        <div class="txtar">
                            <el-input v-model="form.enterpriseIntroduction"
                                      maxlength="500"
                                      type="textarea"
                                      placeholder="集团介绍，500字以内"
                            />
                        </div>
                    </el-form-item>

                    <el-form-item label="品牌介绍：">
                        <div class="txtar">
                            <el-input v-model="form.companyIntroduction"
                                      maxlength="1000"
                                      type="textarea"
                                      :autosize="{ minRows: 2, maxRows: 8 }"
                                      placeholder="品牌介绍，500字以内"
                            />
                        </div>
                    </el-form-item>

                    <el-form-item label="跳转小程序：">
                        <div style="width: 1000px;">
                            <el-radio-group v-model="form.jumpProgram">
                                <el-radio label="不跳转"
                                          value="0"
                                />

                                <el-radio label="跳转"
                                          value="1"
                                />
                            </el-radio-group>
                        </div>
                    </el-form-item>

                    <el-form-item v-if="form.jumpProgram === '1'"
                                  prop="programId"
                                  label="小程序原始Id："
                    >
                        <el-input v-model="form.programId"
                                  placeholder="请输入"
                        />
                    </el-form-item>

                    <el-form-item v-if="form.jumpProgram === '1'"
                                  prop="programAppid"
                                  label="小程序APPID："
                    >
                        <el-input v-model="form.programAppid"
                                  placeholder="请输入"
                        />
                    </el-form-item>
                </el-col>

                <el-col :span="10">
                    <el-form-item prop="companyLogo">
                        <div class="upclass">
                            <FlUpload v-model="form.companyLogo" />

                            <div class="tip">
                                <label class="el-form-item__label">公司Logo</label>
                            </div>
                        </div>
                    </el-form-item>
                </el-col>
            </el-row>
        </div>
    </el-form>
</template>

<style lang="less" scoped>
.el-form {
    display: flex;
    flex-direction: row;
}
.upclass {
    width: 100%;
    height: 100%;
    display: flex;
    flex-direction: column;
    justify-content: center;
    .tip {
        text-align: center;
    }
}
.el-input,
.el-select {
    width: 398px;
}

.el-form-item--default {
    margin-bottom: 18px;
}

.el-upload__text {
    width: 100px;
}

.el-upload__tip {
    margin-top: 80px;
}

:deep(.txtar .el-textarea__inner) {
    width: 400px;
}

.footer {
    width: auto;
    position: relative;
    right: 10px;
    bottom: -12px;
    margin: 10px;
}

.footer button {
    width: 100px;
}

.avatar-uploader {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    text-align: center;
}

.avatar {
    display: block;
    width: 300px;
    height: 300px;
}
</style>
